//
//  QLMADetailAddressVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/20.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMADetailAddressVC.h"
#import "QLMAddreInfoCell.h"

@interface QLMADetailAddressVC ()<BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,BMKLocationServiceDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>{
    
    BMKGeoCodeSearch *_geocodesearch;
    BMKReverseGeoCodeOption *_reverseGeoCodeOption;
    BMKLocationService *_locService;
    BMKPoiSearch *_searcher;
    
    NSString *userAddressIdStr;
    NSInteger selectRow;
    
    BOOL isSelectAddreBool;
    BOOL isTapCellSelBool;
}

@property (nonatomic,strong)NSString *cityStr;
@property (nonatomic,strong)NSString *distriStr;
@property (nonatomic,strong)NSString *addresskeyStr;

@property (nonatomic,strong)UITableView *addrtableview;
@property (nonatomic,strong)NSMutableArray *cityDataArr;

@end

@implementation QLMADetailAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=@"手动新增地址";
    
    selectRow=0;
    _cityDataArr=[NSMutableArray array];
    self.backview.layer.masksToBounds=YES;
    self.backview.layer.cornerRadius=10;
    
    self.backviewTopCons.constant=10;
    
    _addressSelectBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    _searchBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    [_searchBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
    
    if (_isEditable) {
        _cityStr=_addressInfoDic[@"addressProvince"];
        
        _addresskeyStr=_addressInfoDic[@"addressProvince"];
        [_addressSelectBtn setTitle:_addresskeyStr forState:UIControlStateNormal];
        
        _addressDetailTF.text=_addressInfoDic[@"addressVal"];
        userAddressIdStr=_addressInfoDic[@"userAddressId"];
    }

    //初始化检索对象
    _searcher =[[BMKPoiSearch alloc] init];
    _searcher.delegate = self;
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    
    CGRect tableRect = CGRectMake(10, 60+10+10, kScreen_width-20, kScreen_height-80-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight);
    
    _addrtableview=[[UITableView alloc] initWithFrame:tableRect style:UITableViewStylePlain];
    _addrtableview.backgroundColor=[UIColor clearColor];
    _addrtableview.delegate=self;
    _addrtableview.dataSource=self;
    _addrtableview.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    _addrtableview.showsVerticalScrollIndicator=NO;
    _addrtableview.showsHorizontalScrollIndicator=NO;
    _addrtableview.tableFooterView=[UIView new];
    [self.view addSubview:_addrtableview];
    
    if (@available(iOS 11.0, *)) {
        _addrtableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.translucent=YES;
    _geocodesearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    if (!_isEditable) {
        [self initLocationService];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.translucent=NO;
    _geocodesearch.delegate = nil; // 不用时，置nil
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    if (_geocodesearch != nil) {
        _geocodesearch = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Action
#pragma mark 初始化地图，定位
-(void)initLocationService{
    if (_locService==nil) {
        _locService = [[BMKLocationService alloc]init];
        [_locService setDesiredAccuracy:kCLLocationAccuracyBest];
    }
    _locService.delegate = self;
    [_locService startUserLocationService];
}
- (IBAction)searchBtnAction:(UIButton *)sender {
    [self.view endEditing:NO];
    isSelectAddreBool=NO;
    [self _startGeoCodeSearchData];
}

- (IBAction)addressSelectAction:(UIButton *)sender {
    
    [self.view endEditing:NO];
    _addressDetailTF.text=@"";
    _addressDetailTF.placeholder=@"请输入详细地址";
    
    __weak typeof(self) weakSelf = self;
    [BRAddressPickerView showAddressPickerWithDefaultSelected:@[@0, @0, @0] isAutoSelect:YES themeColor:[UIColor redColor] resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
        NSString *title=[NSString stringWithFormat:@"%@%@%@",province,city,area];
        
        weakSelf.addresskeyStr=title;
        [weakSelf.addressSelectBtn setTitle:title forState:UIControlStateNormal];
        
        weakSelf.cityStr=city.name;
        weakSelf.distriStr=area.name;
    }];
//    [BRAddressPickerView showAddressPickerWithDefaultSelected:@[@0, @0, @0] isAutoSelect:YES resultBlock:^(NSArray *selectAddressArr) {
//        NSString *title=[NSString stringWithFormat:@"%@%@%@",selectAddressArr[0],selectAddressArr[1],selectAddressArr[2]];
//
//        weakSelf.addresskeyStr=title;
//        [weakSelf.addressSelectBtn setTitle:title forState:UIControlStateNormal];
//
//        weakSelf.cityStr=selectAddressArr[1];
//        weakSelf.distriStr=selectAddressArr[2];
//    }];
}

- (void)comfireBtnAction{
    
    if ([_addresskeyStr length]==0||_addressDetailTF.text.length==0) {
        ETToast(@"请输入地址");
        return;
    }
    
    if (_cityDataArr.count!=0) {
        MapAddressModel *aselctmodel=(MapAddressModel *)_cityDataArr[selectRow];
        _addressDetailTF.text=aselctmodel.name;
        [self commitAddressAlert:aselctmodel.latitude AndLongitude:aselctmodel.longitude];
    }
}

- (void)_startGeoCodeSearchData{
    
    [self.view makeToastActivity:CSToastPositionCenter];
    
    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    geocodeSearchOption.city=[NSString stringWithFormat:@"%@%@",_distriStr,_cityStr];
    geocodeSearchOption.address = [NSString stringWithFormat:@"%@",_addresskeyStr];
    
    BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
    if(flag){
        NSLog(@"geo检索发送成功");
    }else{
        NSLog(@"geo检索发送失败");
    }
}

- (void)_startSearchAddressData:(CLLocationDegrees)latitude AndLongitude:(CLLocationDegrees)Longitude{
    
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc] init];
    option.pageIndex = 0;
    option.pageCapacity = 20;
    option.location=CLLocationCoordinate2DMake(latitude, Longitude);
    option.keyword = _addressDetailTF.text;
    option.sortType=BMK_POI_SORT_BY_DISTANCE;
    option.radius = 300000;
    
    //发起检索
    BOOL flag = [_searcher poiSearchNearBy:option];//poiSearchNearBy:option
    if (flag) {
        NSLog(@"检索发送成功");
    } else {
        NSLog(@"检索发送失败");
    }
}

#pragma mark - UITextField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    isSelectAddreBool=NO;
    [self _startGeoCodeSearchData];
    return YES;
}

#pragma mark - 请求数据
- (void)reuqestAddressInfoDataWithLatitude:(CLLocationDegrees)latitude AndLongitude:(CLLocationDegrees)Longitude{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    
    NSString *userid=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId];
    NSString *addressDetStr=[NSString stringWithFormat:@"%@",_addressDetailTF.text];
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:userid forKey:@"userId"];
    [paramerDic setObject:_addresskeyStr forKey:@"addressKey"];
    [paramerDic setObject:addressDetStr forKey:@"addressVal"];
    [paramerDic setObject:@(latitude) forKey:@"addressLatitude"];
    [paramerDic setObject:@(Longitude) forKey:@"addressLongitude"];
    
    if (_isEditable) {
        [paramerDic setObject:userAddressIdStr forKey:@"userAddressId"];
    }

    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/saveAddress" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            ETToast(responseObject[@"msg"]);
                            [self.navigationController popViewControllerAnimated:YES];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)commitAddressAlert:(CLLocationDegrees)latitude AndLongitude:(CLLocationDegrees)Longitude{
    
//    __weak QLMADetailAddressVC *weakself = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定添加此地址？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self reuqestAddressInfoDataWithLatitude:latitude AndLongitude:Longitude];
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - BMKLocationServiceDelegate
- (void)didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"error = %@",error);
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    [_locService stopUserLocationService];
    [self _requestAddressNameWithLatitude:userLocation.location.coordinate.latitude andLongtitude:userLocation.location.coordinate.longitude];
}

- (void)_requestAddressNameWithLatitude:(CLLocationDegrees)latitude andLongtitude:(CLLocationDegrees)longtitude{
    
    if (_reverseGeoCodeOption==nil) {
        _reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    }
    //需要逆地理编码的坐标位置
    _reverseGeoCodeOption.reverseGeoPoint = CLLocationCoordinate2DMake(latitude, longtitude);
    [_geocodesearch reverseGeoCode:_reverseGeoCodeOption];
}

#pragma mark - 搜索结果回调
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error{
    [self.view hideToastActivity];
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        [self.cityDataArr removeAllObjects];
        for(BMKPoiInfo *poiInfo in poiResultList.poiInfoList){
            MapAddressModel *model=[[MapAddressModel alloc]init];
            model.name=poiInfo.name;
            model.address=poiInfo.address;
            model.latitude=poiInfo.pt.latitude;
            model.longitude=poiInfo.pt.longitude;
            [self.cityDataArr addObject:model];
        }
        
        //无论是否有数据都需要刷新，否则滑动列表时会报错数组越界
        [_addrtableview reloadData];
        
    }else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        ETToast(@"起始点有歧义");
    } else {
        ETToast(@"抱歉，未找到结果");
        [_cityDataArr removeAllObjects];
        [_addrtableview reloadData];
    }
}

- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{

    [self.view hideToastActivity];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [self _startSearchAddressData:item.coordinate.latitude AndLongitude:item.coordinate.longitude];
    }else{
        ETToast(@"您输入的地址有误，请重新输入！");
    }
}

#pragma mark - BMKReGeoCodeSearchDelegate
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    [self.view hideToastActivity];
    //获取周边用户信息
    if (error==BMK_SEARCH_NO_ERROR) {
        
        _addresskeyStr=[NSString stringWithFormat:@"%@%@%@",result.addressDetail.province,result.addressDetail.city,result.addressDetail.district];
        [_addressSelectBtn setTitle:_addresskeyStr forState:UIControlStateNormal];
        
        if (!isSelectAddreBool) {
            _addressDetailTF.text=result.addressDetail.streetName;
            _cityStr=result.addressDetail.city;
            
            [self.cityDataArr removeAllObjects];
            for(BMKPoiInfo *poiInfo in result.poiList){
                MapAddressModel *model=[[MapAddressModel alloc]init];
                model.name=poiInfo.name;
                model.address=poiInfo.address;
                model.latitude=poiInfo.pt.latitude;
                model.longitude=poiInfo.pt.longitude;
                [self.cityDataArr addObject:model];
                
                if (isTapCellSelBool) {
                    [self comfireBtnAction];
                }
            }
            //无论是否有数据都需要刷新，否则滑动列表时会报错数组越界
            [_addrtableview reloadData];
        }
        
        if (isTapCellSelBool) {
            [self comfireBtnAction];
        }
        
    }else{
        NSLog(@"BMKSearchErrorCode: %u",error);
    }
}

#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor=[UIColor whiteColor];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView=[[UIView alloc] init];
    footerView.backgroundColor=[UIColor clearColor];
    return footerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _cityDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QLMAddreInfoCell *cell=[QLMAddreInfoCell cellWithTableView:tableView];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.tintColor = [UIColor greenColor];
    
    MapAddressModel *model=(MapAddressModel *)_cityDataArr[indexPath.section];
    cell.addrenameLabel.text=model.name;
    cell.addressDetailLabel.text=model.address;
    
    return cell;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    isSelectAddreBool=YES;
    isTapCellSelBool=YES;
    selectRow=indexPath.section;
    
    NSArray *array =[tableView visibleCells];
    for (UITableViewCell *cell in array) {
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MapAddressModel *selctmodel=(MapAddressModel *)_cityDataArr[indexPath.section];
    _addressDetailTF.text=selctmodel.name;
    
    [self _requestAddressNameWithLatitude:selctmodel.latitude andLongtitude:selctmodel.longitude];
}

@end
